package com.gymmsystem.GYMMSystem.controller;

import com.gymmsystem.GYMMSystem.dto.CourseReservationDTO;
import com.gymmsystem.GYMMSystem.entity.Course;
import com.gymmsystem.GYMMSystem.service.CourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/courses")
@RequiredArgsConstructor
@CrossOrigin(origins = "${cors.allowed-origins}", allowCredentials = "true")
@Slf4j
public class CourseController {

    private final CourseService courseService;

    // 在CourseController类中添加新接口
    @GetMapping("/{courseId}/reservation-info")
    public ResponseEntity<CourseReservationDTO> getCourseReservationInfo(@PathVariable Long courseId) {
        try {
            CourseReservationDTO reservationInfo = courseService.getCourseReservationInfo(courseId);
            return ResponseEntity.ok(reservationInfo);
        } catch (Exception e) {
            log.error("获取课程预约信息失败，课程ID: {}", courseId, e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取可预约的课程列表
    @GetMapping("/available")
    public ResponseEntity<List<Course>> getAvailableCourses() {
        List<Course> courses = courseService.getAvailableCourses();
        return ResponseEntity.ok(courses);
    }

    // 获取包含教练详细信息的课程列表
    @GetMapping("/with-coach-info")
    public ResponseEntity<List<Course>> getCoursesWithCoachInfo() {
        List<Course> courses = courseService.getCoursesWithCoachInfo();
        return ResponseEntity.ok(courses);
    }

    // 根据教练ID获取该教练的课程
    @GetMapping("/coach/{coachId}")
    public ResponseEntity<List<Course>> getCoursesByCoach(@PathVariable Long coachId) {
        List<Course> courses = courseService.getCoursesByCoachId(coachId);
        return ResponseEntity.ok(courses);
    }

    // 根据课程ID获取课程详情
    @GetMapping("/{courseId}")
    public ResponseEntity<Course> getCourseById(@PathVariable Long courseId) {
        log.info("获取课程详情请求 - 课程ID: {}", courseId);
        try {
            Course course = courseService.getCourseById(courseId);

            if (course != null) {
                log.info("成功获取课程详情 - 课程ID: {}, 课程名称: {}", courseId, course.getCName());
                return ResponseEntity.ok(course);
            } else {
                log.warn("获取课程详情失败 - 课程不存在，课程ID: {}", courseId);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取课程详情时发生异常 - 课程ID: {}", courseId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 创建新课程
    @PostMapping
    public ResponseEntity<?> createCourse(@RequestBody Course course) {
        try {
            boolean success = courseService.createCourse(course);
            return success ? ResponseEntity.ok("课程创建成功") :
                    ResponseEntity.badRequest().body("课程创建失败");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 更新课程信息
    @PutMapping("/{courseId}")
    public ResponseEntity<?> updateCourse(@PathVariable Long courseId, @RequestBody Course course) {
        log.info("更新课程信息请求 - 课程ID: {}, 课程数据: {}", courseId, course);
        try {
            course.setCId(courseId);
            boolean success = courseService.updateCourse(course);
            if (success) {
                log.info("课程更新成功 - 课程ID: {}", courseId);
                return ResponseEntity.ok("课程更新成功");
            } else {
                log.warn("课程更新失败 - 课程ID: {}", courseId);
                return ResponseEntity.badRequest().body("课程更新失败");
            }
        } catch (Exception e) {
            log.error("课程更新时发生异常 - 课程ID: {}", courseId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新课程时发生内部错误: " + e.getMessage());
        }
    }

    // 下架课程（修改为下架功能，不再删除）
    @PutMapping("/{courseId}/status")
    public ResponseEntity<?> updateCourseStatus(@PathVariable Long courseId, @RequestParam Integer status) {
        boolean success = courseService.updateCourseStatus(courseId, status);
        return success ? ResponseEntity.ok("课程状态更新成功") :
                ResponseEntity.badRequest().body("课程状态更新失败");
    }

    // 图片上传接口
    @PostMapping("/upload-image")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = courseService.uploadCourseImage(file);
            return ResponseEntity.ok(Map.of("imageUrl", imageUrl));
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return ResponseEntity.badRequest().body("图片上传失败: " + e.getMessage());
        }
    }

    // 检查教练在指定时间是否可用
    @GetMapping("/check-availability")
    public ResponseEntity<Boolean> checkCoachAvailability(
            @RequestParam Long coachId,
            @RequestParam String courseTime) {
        boolean available = courseService.checkCoachAvailability(coachId, courseTime);
        return ResponseEntity.ok(available);
    }

    // 检查课程是否还有空位
    // 使用场景：用户预约课程前的容量验证
    @GetMapping("/{courseId}/capacity")
    public ResponseEntity<Boolean> checkCourseCapacity(@PathVariable Long courseId) {
        try {
            boolean hasCapacity = courseService.checkCourseCapacity(courseId);
            return ResponseEntity.ok(hasCapacity);
        } catch (Exception e) {
            log.error("检查课程容量失败，课程ID: {}", courseId, e);
            return ResponseEntity.badRequest().body(false);
        }
    }

    // 获取课程图片URL
    @GetMapping("/{courseId}/image")
    public ResponseEntity<String> getCourseImage(@PathVariable Long courseId) {
        String imageUrl = courseService.getCourseImageUrl(courseId);
        return imageUrl != null ? ResponseEntity.ok(imageUrl) : ResponseEntity.notFound().build();
    }

    // 更新课程图片
    @PutMapping("/{courseId}/image")
    public ResponseEntity<?> updateCourseImage(@PathVariable Long courseId, @RequestBody String imageUrl) {
        boolean success = courseService.updateCourseImage(courseId, imageUrl);
        return success ? ResponseEntity.ok("课程图片更新成功") :
                ResponseEntity.badRequest().body("课程图片更新失败");
    }

    // 管理员分页查询课程列表
    @GetMapping("/admin/page")
    public ResponseEntity<Map<String, Object>> getCoursesByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "6") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String search) {
        Map<String, Object> result = courseService.getCoursesByPage(page, size, status, search);
        return ResponseEntity.ok(result);
    }

    // 管理员获取所有课程
    @GetMapping("/admin/all")
    public ResponseEntity<List<Map<String, Object>>> getAllCourses() {
        List<Map<String, Object>> courses = courseService.getAllCourses();
        return ResponseEntity.ok(courses);
    }

}